//
//  XPPhotoVideoPicker.swift
//  PPKit
//
//  Created by xiaopin on 2021/6/11.
//  Copyright © 2021 scoresdata.net. All rights reserved.
//

import UIKit
import PhotosUI
import MobileCoreServices
/*
 
info.plist必须配置的权限，文案内容根据自己项目功能修改
 
 Privacy - Camera Usage Description： 请授权App允许使用相机采集头像和媒体图片，用来保存到远程仓库中记录
 Privacy - Photo Library Additions Usage Description： 请授权App允许将视频截图保存到相册
 Privacy - Photo Library Usage Description： 请授权App允许使用相册获取头像或媒体图片，用来保存到远程仓库中记录和分享媒体资源
 
 涉及的库：PhotoKit
 
 iOS14之前使用UIImagePickerController来选择照片和视频,只能单选，要支持多选的话选择PhotoKit的第三方组件
 iOS14之后将使用PHPickerViewController来选择照片和视频，支持单多选
 PHPickerViewController
 PHPickerConfiguration
 PHPickerFilter
 PHPickerResult
 
 https://developer.apple.com/documentation/photokit/selecting_photos_and_videos_in_ios
 https://www.jianshu.com/p/5e7aacfa4374
 */

/// 图片媒体资源选择器
class XPPhotoVideoPicker:NSObject{
    
    //MARK: 单例类写法
    static let shared = XPPhotoVideoPicker()
    private override init(){}

    //MARK: 回调闭包
    var selectedImageClosure:((UIImage,URL)->())?
    var selectedVideoClosure:((URL)->())?
    //MARK: 方法
    /// 打开相机
    func openCamera(){
        //检测相机模式是否可用
        if !UIImagePickerController.isSourceTypeAvailable(.camera) {
            showAlert("当前设备不支持拍照!")
            return
        }

        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        imagePicker.allowsEditing = true
        pp_topViewController()?.present(imagePicker, animated: true, completion: nil)
    }
    
    /// 打开照片库
    func openPhotoLibrary(canEdit:Bool = true) -> Self{
        //检测相册模式是否可用
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            showAlert("当前设备不支持访问相册根目录!")
            return self
        }
        
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        imagePicker.mediaTypes = [kUTTypeImage as String]
        imagePicker.allowsEditing = canEdit
        pp_topViewController()?.present(imagePicker, animated: true, completion: nil)
        
        return self
    }
    
    /// 打开视频库
    func openVideoLibrary() -> Self{
        //检测相册模式是否可用
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            showAlert("当前设备不支持访问相册根目录!")
            return self
        }
        
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        imagePicker.mediaTypes = [kUTTypeMovie as String]
        //视频最大时长，默认10分钟
        //imagePicker.videoMaximumDuration = 10
        imagePicker.allowsEditing = false
        pp_topViewController()?.present(imagePicker, animated: true, completion: nil)
        return self
    }
    
    //存放照片资源的标志符
    var localId:String?
    func savePhoto(_ image:UIImage){
        //方法1：
        //UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
        
        //iOS8后新方式
        //简单存储
        PHPhotoLibrary.shared().performChanges {
            PHAssetChangeRequest.creationRequestForAsset(from: image)
        } completionHandler: { (isSuccess, error) in
            if isSuccess {
                PPLog("保存成功")
            }else{
                PPLog("保存失败,\(error!.localizedDescription)")
            }
        }
        
        //存储可获取，保存的图片相册路径，保存的原图，保存的缩略图
        /*
        PHPhotoLibrary.shared().performChanges {
            let result = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let assetPlaceholder = result.placeholderForCreatedAsset
            //保存标志符
            self.localId = assetPlaceholder?.localIdentifier
        } completionHandler: { [weak self] (isSuccess, error) in
            if isSuccess {
                PPLog("保存成功")
                guard let localId = self?.localId else { return }
                //通过标志符获取对应的资源
                let assetResult = PHAsset.fetchAssets(withLocalIdentifiers: [localId], options: nil)
                let asset = assetResult[0]
                let options = PHContentEditingInputRequestOptions()
                options.canHandleAdjustmentData = {(adjustmeta: PHAdjustmentData) -> Bool in
                    return true
                }
                
                //获取保存的图片路径
                asset.requestContentEditingInput(with: options, completionHandler: { (contentEditingInput:PHContentEditingInput?, info: [AnyHashable : Any]) in
                    print("地址：",contentEditingInput!.fullSizeImageURL!)
                })

                //获取保存的原图
                PHImageManager.default().requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: nil, resultHandler: { (image, _:[AnyHashable : Any]?) in
                    //print("获取原图成功：\(image)")
                })
                //获取保存的缩略图
                PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width:100, height:100), contentMode: .aspectFit, options: nil, resultHandler: { (image, _:[AnyHashable : Any]?) in
                    //print("获取缩略图成功：\(image)")
                })
            }else{
                PPLog("保存失败,\(error!.localizedDescription)")
            }
        }
        */
    }
}

//MARK: #委托代理#
extension XPPhotoVideoPicker: UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if picker.sourceType == .photoLibrary {
            let mediaType = info[.mediaType] as? String
            if mediaType == kUTTypeImage as String {
                //获取图片路径（选择后视频会自动复制到app临时文件夹下）
                let imageUrl = info[.imageURL] as! URL
                PPLog("图片地址：\(imageUrl)")
                
                if picker.allowsEditing {
                    //编辑后的图片
                    guard let editedImage = info[.editedImage] as? UIImage else {
                        picker.dismiss(animated: true, completion: nil)
                        return
                    }
                    selectedImageClosure?(editedImage,imageUrl)
                }else{
                    //原图
                    guard let originalImage = info[.originalImage] as? UIImage else {
                        picker.dismiss(animated: true, completion: nil)
                        return
                    }
                    selectedImageClosure?(originalImage,imageUrl)
                }
            }else if mediaType == kUTTypeMovie as String{
                //获取视频路径（选择后视频会自动复制到app临时文件夹下）
                let videoURL = info[.mediaURL] as! URL
                PPLog("视频地址：\(videoURL)")
                //这里需要一个mov转MP4的逻辑
                selectedVideoClosure?(videoURL)
            }
        }else if picker.sourceType == .camera{
            let mediaType = info[.mediaType] as? String
            if mediaType == kUTTypeImage as String {
                //selectedImage
            }
            //UIImageWriteToSavedPhotosAlbum.(self.selectedImage, nil, nil, nil)
        }
        
        picker.dismiss(animated: true) { }
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
}
